<script setup>
import { ref, computed, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import LeaveTable from '@/components/leave/LeaveTable.vue'
import StatusTag from '@/components/common/StatusTag.vue'
import FloatingBackButton from '@/components/common/FloatingBackButton.vue'
import LogoutButton from '@/components/common/LogoutButton.vue'
import { getAdminLeaves, getStats, markLeaveInvalid, cancelAdminLeave } from '@/api'

const router = useRouter()
const openDetail = (id) => router.push(`/student/leave/${id}`)

// 数据
const loading = ref(false)
const stats = ref({ total: 0, pending: 0, approved: 0, rejected: 0 })

const allItems = ref([])

// 获取请假列表
const fetchLeaves = async () => {
  loading.value = true
  try {
    const response = await getAdminLeaves({ page: 1, pageSize: 999 })
    if (response.code === 0 && response.data) {
      const rows = response.data.rows || []
      allItems.value = rows.map((item) => ({
        id: item.id,
        typeLabel: item.type === 'sick' ? '病假' : item.type === 'personal' ? '事假' : '其他',
        timeRange: `${formatDateTime(item.start_at)} ~ ${formatDateTime(item.end_at)}`,
        start: item.start_at,
        end: item.end_at,
        hours: item.hours,
        status: item.status,
        studentName: item.student_name || '未知',
      }))
    }
  } catch (error) {
    console.error('获取请假列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await getStats()
    if (response.code === 0 && response.data) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取统计失败:', error)
  }
}

// 格式化时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

// 分页：每页 10 条
// 筛选条件
const filterStatus = ref('') // '', pending, approved, rejected, cancelled, invalid
const filterType = ref('') // '', 事假/病假
const keyword = ref('') // 学生姓名
const dateStart = ref('')
const dateEnd = ref('')

// 排序
const sortBy = ref('start') // start | hours | status
const sortOrder = ref('desc') // asc | desc

// 分页：每页 10 条
const pageSize = 10
const currentPage = ref(1)
const total = computed(() => filteredSorted.value.length)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize)))
const filtered = computed(() => {
  const ks = keyword.value.trim()
  const ds = dateStart.value ? new Date(dateStart.value).getTime() : null
  const de = dateEnd.value ? new Date(dateEnd.value).getTime() : null
  return allItems.value.filter((it) => {
    if (filterStatus.value && it.status !== filterStatus.value) return false
    if (filterType.value && it.typeLabel !== filterType.value) return false
    if (ks && !String(it.studentName).includes(ks)) return false
    if (ds || de) {
      const t = new Date(it.start).getTime()
      if (ds && t < ds) return false
      if (de && t > de) return false
    }
    return true
  })
})

const statusWeight = (s) =>
  ({ approved: 3, pending: 2, rejected: 1, cancelled: 0, invalid: -1 })[s] ?? -2
const filteredSorted = computed(() => {
  const arr = [...filtered.value]
  arr.sort((a, b) => {
    let va
    let vb
    if (sortBy.value === 'hours') {
      va = a.hours
      vb = b.hours
    } else if (sortBy.value === 'status') {
      va = statusWeight(a.status)
      vb = statusWeight(b.status)
    } else {
      va = new Date(a.start).getTime()
      vb = new Date(b.start).getTime()
    }
    const res = va === vb ? 0 : va > vb ? 1 : -1
    return sortOrder.value === 'asc' ? res : -res
  })
  return arr
})

const pagedItems = computed(() => {
  const startIdx = (currentPage.value - 1) * pageSize
  return filteredSorted.value.slice(startIdx, startIdx + pageSize)
})

const goPage = (p) => {
  if (p < 1 || p > totalPages.value) return
  currentPage.value = p
}

// 管理员操作
const markInvalid = async (id) => {
  try {
    const response = await markLeaveInvalid(id)
    if (response.code === 0) {
      const it = allItems.value.find((x) => x.id === id)
      if (it) {
        it.status = 'invalid'
      }
      alert('已标记为无效')
    } else {
      alert('操作失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('标记无效失败:', error)
    alert('操作失败，请检查网络连接')
  }
}

const revoke = async (id) => {
  try {
    const response = await cancelAdminLeave(id)
    if (response.code === 0) {
      const it = allItems.value.find((x) => x.id === id)
      if (it) {
        it.status = 'cancelled'
      }
      alert('已撤销')
    } else {
      alert('操作失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('撤销失败:', error)
    alert('操作失败，请检查网络连接')
  }
}

const loadData = () => {
  fetchLeaves()
  fetchStats()
}

onMounted(() => {
  loadData()
})

// 每次页面激活时刷新数据
onActivated(() => {
  loadData()
})
</script>

<template>
  <div class="page">
    <div class="container">
      <div class="header">
        <h2>请假管理</h2>
        <div class="actions">
          <button class="btn ghost">导出 CSV</button>
        </div>
      </div>
      <!-- 统计概览 -->
      <div class="stats">
        <div class="card elevated">
          <div class="num" style="color: #666">{{ stats.total }}</div>
          <div class="label">总申请</div>
        </div>
        <div class="card elevated">
          <div class="num" style="color: var(--color-primary)">{{ stats.pending }}</div>
          <div class="label">待审批</div>
        </div>
        <div class="card elevated">
          <div class="num" style="color: var(--color-success)">{{ stats.approved }}</div>
          <div class="label">已通过</div>
        </div>
      </div>

      <!-- 筛选工具条 -->
      <div class="filters card elevated">
        <div class="row">
          <div class="field">
            <label>状态</label>
            <select v-model="filterStatus">
              <option value="">全部</option>
              <option value="pending">待审批</option>
              <option value="approved">已通过</option>
              <option value="rejected">已驳回</option>
              <option value="cancelled">已撤销</option>
              <option value="invalid">无效</option>
            </select>
          </div>
          <div class="field">
            <label>类型</label>
            <select v-model="filterType">
              <option value="">全部</option>
              <option value="事假">事假</option>
              <option value="病假">病假</option>
            </select>
          </div>
          <div class="field">
            <label>学生</label>
            <input v-model="keyword" placeholder="姓名关键词" />
          </div>
          <div class="field">
            <label>开始日期</label>
            <input v-model="dateStart" type="date" />
          </div>
          <div class="field">
            <label>结束日期</label>
            <input v-model="dateEnd" type="date" />
          </div>
          <div class="field">
            <label>排序</label>
            <div class="sorter">
              <select v-model="sortBy">
                <option value="start">申请时间</option>
                <option value="hours">时长</option>
                <option value="status">状态</option>
              </select>
              <select v-model="sortOrder">
                <option value="desc">降序</option>
                <option value="asc">升序</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <LeaveTable :items="pagedItems" role="admin">
        <template #status="{ status }">
          <StatusTag :status="status" size="sm" />
        </template>
        <template #actions="{ row }">
          <button class="link" @click="openDetail(row.id)">详情</button>
          <button class="link danger" @click="revoke(row.id)">撤销</button>
          <button class="link muted" @click="markInvalid(row.id)">标记无效</button>
        </template>
      </LeaveTable>

      <div class="pagination">
        <button class="pager" :disabled="currentPage === 1" @click="goPage(currentPage - 1)">
          上一页
        </button>
        <span class="page-info"
          >第 {{ currentPage }} / {{ totalPages }} 页（共 {{ total }} 条）</span
        >
        <button
          class="pager"
          :disabled="currentPage === totalPages"
          @click="goPage(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>
    <FloatingBackButton />
    <LogoutButton />
  </div>
</template>

<style scoped>
.page {
  position: fixed;
  inset: 0;
  padding: 32px 24px;
  overflow: auto;
  background:
    radial-gradient(circle at 20% 10%, rgba(255, 105, 0, 0.04) 0%, transparent 40%),
    radial-gradient(circle at 80% 90%, rgba(255, 105, 0, 0.04) 0%, transparent 40%);
}
.container {
  width: 100%;
  max-width: 1120px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header h2 {
  font-size: 22px;
  color: #1d1d1f;
}
.stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}
.stats .card {
  text-align: center;
  padding: 20px;
}
.filters {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.filters .row {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 12px;
}
.filters .field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.filters label {
  font-size: 12px;
  color: var(--muted-text);
}
.filters select,
.filters input[type='date'],
.filters input[type='text'],
.filters input {
  padding: 10px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #fff;
}
.filters .sorter {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}
.btn.ghost {
  background: #fff;
  border: 1px solid #e5e7eb;
  padding: 10px 14px;
  border-radius: 8px;
  cursor: pointer;
}
.link {
  background: transparent;
  border: none;
  color: var(--color-primary);
  cursor: pointer;
  font-weight: 600;
}
.link.danger {
  color: var(--color-danger);
}
.link.muted {
  color: var(--muted-text);
}
.num {
  font-size: 24px;
  font-weight: 800;
}
.label {
  color: var(--muted-text);
}
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}
.pager {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 8px 12px;
  cursor: pointer;
}
.pager:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.page-info {
  color: var(--muted-text);
}
</style>
